package com.lagou.controller;

import com.lagou.entity.AuthCode;
import com.lagou.service.CodeService;
import com.lagou.service.remote.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private CodeService codeService;
    @Autowired
    private EmailService emailService;

    /**
     * ⽣生成验证码并发送到对应邮箱
     *
     * @param email
     * @return
     */
    @RequestMapping("/create/{email}")
    public boolean createCodeAndSend(@PathVariable("email") String email) {
        // 创建验证码
        AuthCode authCode = codeService.createCode(email);

        // 发送验证码
        emailService.sendEmail(email, authCode.getCode());

        return true;
    }

    /**
     * 校验验证码
     *
     * @param email
     * @param code
     * @return 0-正确 1-错误 2-超时
     */
    @RequestMapping("/validate/{email}/{code}")
    public int validateCode(@PathVariable("email") String email,
                        @PathVariable("code") String code) {

        AuthCode authCode = codeService.getCode(code);
        if (authCode == null || !authCode.getEmail().equals(email)) {
            return 1;
        } else if (authCode.getExpireTime().before(new Date())) {
            return 2;
        }
        return 0;
    }

}
